<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <el-tab-pane v-if="$store.getters.role === 1" label="全部题目" name="0" />
    </el-tabs>
    <div class="filter-container">
      <el-form :model="query" :inline="true" size="mini" label-position="right" label-width="70px">
        <el-form-item label="题目">
          <el-input v-model="query.title" placeholder="题目" suffix-icon="xxxx" />
        </el-form-item>
        <el-form-item label="知识点">
          <el-input v-model="query.pointName" placeholder="知识点" suffix-icon="xxxx" />
        </el-form-item>

        <el-form-item label="题目类型">
          <el-select v-model="query.type" size="mini" placeholder="请选择题目类型">
            <el-option v-for="(key, value) in questionType" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="科目">
          <el-cascader v-model="query.subjectId" :options="subjects">
          </el-cascader>
        </el-form-item>
        <el-form-item label="上线状态">
          <el-select v-model="query.onlineStatus" clearable>
            <el-option label="上线" value="1" />
            <el-option label="下线" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button size="mini" icon="el-icon-search" type="primary" plain @click="getQuestionList(0)">查询</el-button>
          <el-button size="mini" icon="el-icon-refresh-right"
            @click="query = { pageNo: 1, pageSize: 20, total: 0 }">重置</el-button>
        </el-form-item>
      </el-form>
      <div style="margin-top: 10px">
        <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit">
          <router-link to="/questionInfo">添加题目</router-link>
        </el-button>
        <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="showImageDialog">
          图片识别
        </el-button>
        
        <!-- 图片识别弹框 -->
        <el-dialog title="图片识别" :visible.sync="imageDialogVisible" width="30%" v-loading="imageRecognitionLoading">
          <el-form :model="imageForm" label-width="80px" :rules="imageFormRules" ref="imageForm">
            <el-form-item label="科目" prop="subjectId" required>
              <el-cascader v-model="imageForm.subjectId" :options="subjects"></el-cascader>
            </el-form-item>
            <el-form-item label="图片" prop="imageUrl" required>
              <el-upload
                class="upload-demo"
                action="https://mangerapi.star.91yunshi.com/common/file"
                :headers="uploadHeaders"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                :limit="1">
                <el-button size="small" type="primary">选择图片</el-button>
                <div slot="tip" class="el-upload__tip">请确保图片题目完整（支持jpg/png格式）</div>
              </el-upload>
            </el-form-item>
            <div style="color: #e83255;
            font-size: 11px;
            text-align: center;">*请确保图片题目完整,可多题上传</div>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="imageDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleImageRecognition">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
    <el-table v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row
      style="width: 100%; margin-top: 10px" :row-class-name="tableRowClassName" @expand-change="expandChange">

      <!-- <el-table-column
        :selectable="selectEnable"
        type="selection"
        width="55"
      >
      </el-table-column> -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table v-loading="listLoading" :data="sublist"  row-key="id" border fit highlight-current-row
            style="width: 100%; margin-top: 10px" :row-class-name="tableRowClassName">
            <el-table-column min-width="200px" max-height="50px" align="center" :show-overflow-tooltip="true"
              label="题目">
              <template slot-scope="scope">
                <span >{{scope.row.title}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :show-overflow-tooltip="true" label="知识点">
              <template slot-scope="scope">
                {{scope.row.knowledgePoints}}
              </template>
            </el-table-column>
            <el-table-column min-width="50" align="center" label="题目类型">
              <template slot-scope="scope">
                <span>{{ questionType[scope.row.type] }}</span>
              </template>
            </el-table-column>

            <el-table-column class-name="status-col" align="center" label="题目状态" width="140px">
              <template slot-scope="scope">
                <el-tag :type="scope.row | tag">{{ scope.row | status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column width="200px" align="center" label="创建时间">
              <template slot-scope="scope">
                <span>{{ scope.row.ctime | parseTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <router-link :to="{
              path: '/questionInfo',
              query: {
                id: scope.row.id,
                activeName: activeName,
              },
            }">
                  <el-button type="primary" size="mini">编辑</el-button>
                </router-link>
                <el-button size="mini" v-if="scope.row.onlineStatus==1"
                  @click="onlineQuestions(scope.row.id,2)">下线</el-button>
                <el-button type="primary" size="mini" v-if="scope.row.onlineStatus==2"
                  @click="onlineQuestions(scope.row.id,1)">上线</el-button>
                <el-button v-if="scope.row.onlineStatus == 2" type="danger" @click="delQuestion(scope.row.id)"
                  size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column min-width="200px" max-height="50px" align="center" :show-overflow-tooltip="true" label="题目/材料">
        <template slot-scope="scope">
          <span  style="max-height: 50px !important;">
            {{scope.row.title}}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" :show-overflow-tooltip="true" label="知识点">
        <template slot-scope="scope">
          {{scope.row.knowledgePoints}}
        </template>
      </el-table-column>
      <el-table-column min-width="50" align="center" label="题目类型">
        <template slot-scope="scope">
          <span>{{ questionType[scope.row.type] }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" align="center" label="题目状态" width="140px">
        <template slot-scope="scope">
          <el-tag :type="scope.row | tag">{{ scope.row | status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="200px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.ctime | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <router-link :to="{
              path: '/questionInfo',
              query: {
                id: scope.row.id,
                activeName: activeName,
              },
            }">
            <el-button type="primary" size="mini">编辑</el-button>
          </router-link>
          <el-button size="mini" v-if="scope.row.onlineStatus==1"
            @click="onlineQuestions(scope.row.id,2)">下线</el-button>
          <el-button type="primary" size="mini" v-if="scope.row.onlineStatus==2"
            @click="onlineQuestions(scope.row.id,1)">上线</el-button>
          <el-button v-if="scope.row.onlineStatus == 2" type="danger" @click="delQuestion(scope.row.id)"
            size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="query.pageNo" :page-sizes="[10, 20, 30, 40]" :page-size="query.pageSize"
      :total="query.total" layout="total, sizes, prev, pager, next, jumper" background class="page"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script>
  import waves from "@/directive/waves";
import { parseTime } from "@/utils/index";
import store from '@/store';
import {
  questionList,
  delQuestionAll,
  commitCheck,
  rejectCheckMultiple,
  onlineQuestion,
  imageQuestionWorkflow
} from "@/api/question.js";
import { getSubjectList } from "@/api/subjectType.js";
  export default {
    name: "QuestionList",
    directives: { waves },
    filters: {
      parseTime(time) {
        return parseTime(time);
      },
      tag(row) {
        if (row.status === 1) {
          return "success";
        }
        if (row.editStatus !== 1) {
          return "info";
        }
        if (row.checkStatus !== 1) {
          return "warning";
        }
        if (row.reviewStatus === 1) {
          return "success";
        }
        return "";
      },
      status(row) {
        if (row.onlineStatus === 1) {
          return "上线";
        }
        if (row.status === 0) {
          return "编辑中";
        }
        return "下线";
      },
    },
    data() {
      return {
        imageDialogVisible: false,
        imageRecognitionLoading: false,
        imageForm: {
          subjectId: [],
          imageUrl: ''
        },
        imageFormRules: {
          subjectId: [{ required: true, message: '请选择科目', trigger: 'change' }],
          imageUrl: [{ required: true, message: '请上传图片', trigger: 'change' }]
        },
        questionType: {
          1: "单选题",
          2: "多选题",
          3: "判断题",
          4: "填空",
          5: "简答题",
          6: "材料题",
          7: "连线题",
        },
        listLoading: false,
        list: [],
        subjects: [],
        activeName: "0",
        query: {
          pageNo: 1,
          pageSize: 20,
          total: 0,
        },
        sublist: [],
        selectIds: [],
        teacher: [],
        question: {
          status: 0,
          id: 1,
          checkPeople: "",
        },
        isDel: true,
        parentId: 0
      };
    },
    computed: {
      uploadHeaders() {
        return {
          'Authorization': 'Bearer ' + store.getters.token
        }
      }
    },
    watch: {
      selectIds: {
        handler(val, oldVal) {
          if (val.length > 0) {
            this.isDel = false;
          } else {
            this.isDel = true;
          }
        },
        deep: true, //true 深度监听
      },
    },
    created() {
      this.activeName = "0";
      this.getSubject()
      this.getQuestionList(0);
    },
    methods: {
      showImageDialog() {
        this.imageDialogVisible = true;
        this.imageForm.subjectId = [];
        this.imageForm.imageUrl = '';
        if (this.$refs.imageForm) {
          this.$refs.imageForm.resetFields();
        }
      },
      
      handleUploadSuccess(response, file) {
        console.log(response);
        if (response.code == 0) {
          this.$message.success('上传成功');
          this.imageForm.imageUrl = response.data.url;
        } else {
          this.$message.error(response.msg || '上传失败');
        }
      },
      
      handleUploadError() {
        this.$message.error('上传失败');
      },
      
      beforeUpload(file) {
        const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isImage) {
          this.$message.error('只能上传jpg/png格式的图片！');
          return false;
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$message.error('图片大小不能超过5MB！');
          return false;
        }
        return true;
      },
      
      handleImageRecognition() {
        this.$refs.imageForm.validate((valid) => {
          if (valid) {
            // 只获取最后一级科目ID
            const subjectId = this.imageForm.subjectId[this.imageForm.subjectId.length - 1];
            console.log('最后一级科目ID:', subjectId);
            console.log('图片地址:', this.imageForm.imageUrl);
            
            // 设置加载状态
            this.imageRecognitionLoading = true;
            
            // 调用图片识别接口
            this.$message.info('正在识别图片，请稍候...');
            imageQuestionWorkflow(this.imageForm.imageUrl, subjectId).then((res) => {
              console.log('图片识别结果:', res);
              if (res.code == 0) {
                this.$message.success('图片识别成功');
                // 清空表单数据
                this.imageForm.subjectId = [];
                this.imageForm.imageUrl = '';
                if (this.$refs.imageForm) {
                  this.$refs.imageForm.resetFields();
                }
                // 关闭弹窗
                this.imageDialogVisible = false;
                // 刷新列表
                this.getQuestionList(0);
              } else {
                this.$message.error(res.msg || '图片识别失败');
              }
            }).catch((error) => {
              console.error('图片识别错误:', error);
              this.$message.error('图片识别失败，请重试');
            }).finally(() => {
              // 无论成功或失败，都关闭加载状态
              this.imageRecognitionLoading = false;
            });
          } else {
            return false;
          }
        });
      },

      expandChange(row, expandedRows) {
        this.parentId = row.id
        this.sublist = []
        questionList({ parentId: row.id, pageNo: 1, pageSize: 100 }).then((res) => {
          this.sublist = res.data.list;
        });
      },
      onlineQuestions(id, status) {
        onlineQuestion(id, status).then((res) => {
          this.getQuestionList(0);
          console.log(this.parentId);
          if (this.parentId != 0) {
            this.sublist = []
            questionList({ parentId: this.parentId, pageNo: 1, pageSize: 100 }).then((res) => {
              this.sublist = res.data.list;
            });
          }
        });
      },
      tableRowClassName({ row, rowIndex }) {
        if (row.qualifiedStatus == '1') {
          return 'success-row';
        }
        return '';
      },
      commitCheck() {
        const h = this.$createElement;
        this.$msgbox({
          title: "提交校验",
          message: h(SelectTeacher, {
            props: { value: this.question, teacher: this.teacher },
          }),
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            done();
          },
        })
          .then((res) => {
            this.selectIds.forEach((item) => {
              commitCheck(item, this.question.checkPeople).then((res) => {
                this.getQuestionList();
              });
            });
          })
          .catch((err) => console.log(err));
      },
      selectEnable(row, rowIndex) {
        if (this.activeName === "1") {
          return row.editStatus != 1;
        } else if (this.activeName === "2") {
          return row.checkStatus == 0;
        } else {
          return false;
        }
      },
      handleSelectionChange(val) {
        this.selectIds = val.map((res) => res.id);
      },
      getSubject() {
        getSubjectList().then((res) => {
          const transformData = (data) => {
            return data.map(item => ({
              value: item.id,
              label: item.name,
              children: item.children ? transformData(item.children) : undefined
            }));
          };
          this.subjects = transformData(res.data);
        });
      },
      getQuestionList(parentId) {
        this.listLoading = true;
        this.query.activeName = this.activeName;
        this.query.sort = "desc_q.ctime";
        if (!this.query.year) {
          delete this.query.year;
        }
        if (this.query.subjectId) {
          console.log(this.query.subjectId);
          this.query.subjectId = this.query.subjectId[this.query.subjectId.length - 1];
        }
        this.query.parentId = parentId
        questionList(this.query).then((res) => {
          console.log(res);
          this.list = res.data.list;
          this.query.total = res.data.total;
          this.listLoading = false;
        });
      },
      handleSizeChange(val) {
        this.query.pageSize = val;
        this.query.pageNo = 1;
        this.getQuestionList(0);
      },
      handleCurrentChange(val) {
        this.query.pageNo = val;
        this.getQuestionList(0);
      },
      delQuestionAll() {
        if (this.selectIds.length <= 0) {
          this.$message({
            message: "请选择需要删除的题目",
            type: "warning",
          });
          return;
        }
        this.$confirm("此操作将永久删除选中题目, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delQuestionAll(this.selectIds).then((res) => {
              this.$message({
                message: "批量删除成功",
                type: "success",
              });
              this.getQuestionList();
            });
          })
          .catch(() => { });
      },
      delQuestion(id) {
        let ids = [];
        ids.push(id);
        this.$confirm("此操作将永久删除该题目, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delQuestionAll(ids).then((res) => {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getQuestionList();
            });
          })
          .catch(() => { });
      },
      rejectCheckMultiple() {
        if (this.selectIds.length <= 0) {
          this.$message({
            message: "请选择需要驳回的题目",
            type: "warning",
          });
          return;
        }
        this.$confirm("此操作将驳回选中的题目, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            rejectCheckMultiple(this.selectIds).then((res) => {
              this.$message({
                message: "驳回成功",
                type: "success",
              });
              this.getQuestionList();
            });
          })
          .catch(() => { });
      },
    },
  };
</script>

<style>
  .sortable-ghost {
    opacity: 0.8;
    color: #fff !important;
    background: #42b983 !important;
  }

  .el-table .success-row {
    color: #DCDFE6;
  }

  .sortable-ghost {
    opacity: 0.8;
    color: #fff !important;
    background: #42b983 !important;
  }
</style>

<style scoped>
  .page {
    margin-top: 10px;
  }

  .icon-star {
    margin-right: 2px;
  }

  .drag-handler {
    width: 20px;
    height: 20px;
    cursor: pointer;
  }

  .show-d {
    margin-top: 15px;
  }

</style>